package com.xiongda.service.impl;

import com.xiongda.common.ServerResponse;
import com.xiongda.dao.BlogMapper;
import com.xiongda.dao.CommentMapper;
import com.xiongda.pojo.BlogWithBLOBs;
import com.xiongda.service.BlogService;
import com.xiongda.tools.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 博客服务层实现
 *
 * @author 缪琼
 */
@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public ServerResponse getBlog(Long id) {
        BlogWithBLOBs blog = blogMapper.getBlog(id);
        if (blog == null)
            return ServerResponse.createByErrorMessage("参数错误");
        // 阅读+1
        blog.setReadCount(blog.getReadCount() + 1);
        int count = blogMapper.updateByPrimaryKey(blog);
        if (count != 1)
            return ServerResponse.createByErrorMessage("参数错误");
        return ServerResponse.createBySuccess("获取成功", blog);
    }

    @Override
    public ServerResponse getBlogByUser(Long userId, Integer pageNo, Integer pageSize) {
        Page page = new Page(pageNo, pageSize);
        Map<String, Object> map = page.setPageParams();
        map.put("userId", userId);
        List<BlogWithBLOBs> list = blogMapper.getBlogList(map);
        page.setItems(list);
        Integer total = blogMapper.getTotal(map);
        page.setTotal(total);
        return ServerResponse.createBySuccess("获取成功", page);
    }

    @Override
    public ServerResponse saveAndEditBlog(BlogWithBLOBs blog) {
        int count;
        if (blog.getId() == null) {
            if (blog.getTitle() == null)
                return ServerResponse.createByErrorMessage("该文章缺少标题");
            if (blog.getContent() == null)
                return ServerResponse.createByErrorMessage("该文章缺少内容");
            if (blog.getBackgroundStyle() == null)
                blog.setBackgroundStyle(0);
            if (blog.getIsComment() == null)
                blog.setIsComment(1);
            count = blogMapper.insert(blog);
        }
        else {
            blog.setEditCount(blogMapper.getBlog(blog.getId()).getEditCount() + 1);
            blog.setUpdateTime(new Date());
            count = blogMapper.updateByPrimaryKeySelective(blog);
        }
        if (count != 1)
            return ServerResponse.createByError();
        return ServerResponse.createBySuccess();
    }

}
